<?php
namespace Admin\Controller;
use Think\AjaxPage;
use Think\Page;

class   CrmController extends BaseController{
    public function _initialize(){
        parent::_initialize();
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }else{
            $lastweek = date('Y-m-d 00:00',strtotime("-15 day"));//30天前-1 month
            $begin = I('begin',$lastweek);
            $end =  I('end',date('Y-m-d 23:59'));
        }
        $this->begin = strtotime($begin);
        $this->end = strtotime($end);//+86399;
        $this->assign('timegap',date('Y-m-d H:i',$this->begin).' - '.date('Y-m-d H:i',$this->end));
        $this->assign('begin',date('Y-m-d H:i',$this->begin));
    }
    
    public function delHandle(){
        if(IS_POST){
            $_id = $_POST['del_id'];
            if($_id){
                $r = D('visit')->where('id='.$_id)->delete();
                if($r) exit(json_encode(1));
            }else{
                exit(json_encode(0));
            }
        }
    }
    
    public function delplan(){
        if(IS_POST){
            $_id = $_POST['del_id'];
            if($_id){
                $r = D('plan')->where('id='.$_id)->delete();
                if($r) exit(json_encode(1));
            }else{
                exit(json_encode(0));
            }
        }
    }
    
    public function visitList(){
        $Visit =  M('visit');
        $where = "1=1";
        
        $keywords = I('keywords',false);
        if($keywords){
            $where .= " and visit_name like '%$keywords%'";
        }
        $user_name = I('user_name',false);
        $user_id = I('user_id',false);
        if($user_id){
            $where .= " and user_id =".$user_id;
        }
        if(session('fenbu_id')){
            $where .= " and fenbu_id =".session('fenbu_id');
        }
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if($begin && $end){
            $where .= " and visit_time >=".$begin." and visit_time<=$end";
        }
        $count = $Visit->where($where)->count();// 查询满足要求的总记录数
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $res = $Visit->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $users_arr = [];
        $users = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($users as $key=>$val) {
            $users_arr[$val['user_id']] = $val;
        }
        
        $customer_arr = [];
        $customer = M('customer a')->join('ty_users c on c.user_id=a.custom_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($customer as $key=>$val) {
            $customer_arr[$val['custom_id']] = $val;
        }
        
        foreach($res as $key=>$val) {
            $total = 0;
            if($users_arr[$val['user_id']]){
                $res[$key]['user_id'] = $users_arr[$val['user_id']]['company'];
            }
            if($customer_arr[$val['custom_id']]){
                $total = M('order')->where('order_status not in(3,4) and pay_status not in(3,5) and add_time >= '.$val['visit_time'].' and user_id='.$val['custom_id'])->sum('total_amount');
                $res[$key]['total'] = $total;
                $res[$key]['custom_id'] = $users_arr[$val['custom_id']]['nickname'];
                $res[$key]['custom_name'] = $customer_arr[$val['custom_id']]['company']?$customer_arr[$val['custom_id']]['company']:$customer_arr[$val['custom_id']]['nickname'];
            }
            $res[$key]['visit_time'] = date('Y-m-d', $val['visit_time']);
            $visit_purpose ="";
            if($val['visit_purpose'] == 0){
                $visit_purpose = "收集客户需求";
            }elseif($val['visit_purpose'] == 1){
                $visit_purpose = "了解客户需求";
            }elseif($val['visit_purpose'] == 2){
                $visit_purpose = "方案沟通";
            }elseif($val['visit_purpose'] == 3){
                $visit_purpose = "商务洽谈";
            }else{
                $visit_purpose = "售后服务";
            }
            $res[$key]['visit_purpose'] = $visit_purpose;
        }
        //         $ad_position_list = M('AdPosition')->getField("position_id,position_name,is_open");
        //         $this->assign('ad_position_list',$ad_position_list);//广告位
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$res);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    
    public function addvisit(){
        $act = I('act',false);
        $vis_id = I('vis_id',false);
        $id = I('id',false);
        if(IS_POST){
            $visit_name = $_POST['visit_name'];
            $user_id = $_POST['user_id'];
            $visit_time = $_POST['visit_time'];
            $custom_id = $_POST['custom_id'];
            $visit_purpose = 1;
            $remark = $_POST['remark'];
            if(empty($visit_name)){
                $this->error("任务名称不能为空！");
            }
            if(empty($user_id)){
                $this->error("业务员不能为空！");
            }
            if(empty($visit_time)){
                $this->error("拜访时间不能为空！");
            }
            if(empty($custom_id)){
                $this->error("拜访客户不能为空！");
            }
            
            $users = M('staff')->where("user_id='$user_id'")->find();
            if(empty($users)){
                $this->error("业务员不存在");
            }
            
            $custom = M('customer')->where("custom_id='$custom_id'")->getField('custom_id');
            if(empty($custom)){
                $this->error("客户不存在");
            }
            
            $data['visit_name'] = $visit_name;
            $data['user_id'] = $user_id;
            $data['visit_time'] = strtotime($visit_time);
            $data['custom_id'] = $custom_id;
            $data['visit_purpose'] = $visit_purpose;
            $data['remark'] = $remark;
            $data['fenbu_id'] = $users['fenbu_id'];
            if(!$id){
                $r = D('visit')->add($data);
                if($r){
                    $this->success('任务添加成功',U('Crm/visitList'));
                    exit;
                }else{
                    $this->error("任务更新失败");
                }
            }else{
                $r = D('visit')->where('id='.$id)->save($data);
                if($r){
                    $this->success('任务更新成功',U('Crm/visitList'));
                    exit;
                }else{
                    $this->error("任务更新失败");
                }
            }
            
        }
        if($act == 'edit'){
            if(!$vis_id){
                $this->error("参数错误");
            }
            $visit_data = D('visit')->where('id = '.$vis_id)->find();
            $user_data = D('users')->where('user_id = '.$visit_data['user_id'])->find();
            $custom_data = D('users')->where('user_id = '.$visit_data['custom_id'])->find();
            $visit_data['custom_name'] = $custom_data['company'];
            $visit_data['user_name'] = $user_data['company'];
            $this->assign('visit_data',$visit_data);
        }else{
            $visit_data['visit_time'] = strtotime(date('Y-m-d'));
            $this->assign('visit_data',$visit_data);
        }
        
        $this->display();
    }
    
    
    public function planList(){
        $plan =  M('plan');
        $where = "1=1";
        $type = I('extraParam',0);
        $user_name = I('user_name',false);
        $user_id = I('user_id',false);
        if($user_name && $user_id){
            $where .= " and user_id =".$user_id;
        }
        // $timegap = I('timegap');
        // if($timegap){
        //     $gap = explode(' - ', $timegap);
        //     $begin = strtotime($gap[0]);
        //     $end = strtotime($gap[1]);
        // }
        
        // if($begin && $end){
        //     $where .= " and start_time >=".$begin." and end_time<=$end";
        // }
        if(session('fenbu_id')){
            $where .= " and fenbu_id =".session('fenbu_id');
        }
        if($type){
            $where .= " and status = $type";
        }
        
        $count = $plan->where($where)->count();// 查询满足要求的总记录数
        
        $Page = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数
        $res = $plan->where($where)->order('id desc')->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $users_arr = [];
        $users = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($users as $key=>$val) {
            $users_arr[$val['user_id']] = $val;
        }
        
        foreach($res as $key=>$val) {
            $res[$key]['progress'] = 0;
            if($users_arr[$val['user_id']]){
                $res[$key]['user_name'] = $users_arr[$val['user_id']]['nickname'];
                $res[$key]['company'] = $users_arr[$val['user_id']]['company'];
            }
            $res[$key]['time'] = date('Y-m-d', $val['start_time']).'到'.date('Y-m-d', $val['end_time']);
            $res[$key]['status'] = '进行中';
            if($val['end_time']>time()){
                $diffSeconds = abs($val['end_time'] - time());
                $days = floor($diffSeconds / 86400);
                $res[$key]['days'] = $days;
            }else{
                $res[$key]['days'] = 0;
            }
            //计算订单
            
            $total = M('order')->where('order_status not in(3,4) and add_time >= '.$val['start_time'].' and add_time <= '.$val['end_time'].' and pay_status not in(3,5) and user_id in('.$val['customer_id_arr'].')')->field('order_id')->select();
            
            //有订单数据
            $order_arr = '';
            if($total){
                foreach($total as $keys=>$vals) {
                    $order_arr .= $vals['order_id'].',';
                }
                $order_arr = substr($order_arr, 0, -1);
            }
            
            if($order_arr){
                $order_goods = M('order_goods')->where('order_id in('.$order_arr.')')->field('goods_id,goods_price,goods_num,points,points_fenbu')->select();
            }
            
            //得到计算分类的goods_id和禁止计算产品分类的goods_id
            $category_id_arr = explode(',', $val['category_id_arr']);
            $excludecategory_id_arr = explode(',', $val['excludecategory_id_arr']);//得到排除的产品分类
            $category_id_arr = array_diff($category_id_arr, $excludecategory_id_arr);
            $category_id_arr = implode(',', $category_id_arr);//得到包含的产品分类
            
            if($val['excludecategory_id_arr']){
                $goods_arr_exclude = M('goods')->where('cat_id2 in('.$val['excludecategory_id_arr'].')')->field('goods_id,cat_id2')->select();
                if($goods_arr_exclude){
                    $order_goods = $this->filter_array1_by_id($order_goods,$goods_arr_exclude);//排除相同的元素，$goods_arr_exclude不包含的产品
                }
            }
            
            if($category_id_arr){
                $goods_arr = M('goods')->where('cat_id2 in('.$category_id_arr.')')->field('goods_id,cat_id2')->select();
                if($goods_arr){
                    $order_goods = $this->filter_array1_by_difid($order_goods,$goods_arr);//排除不要同的元素，$goods_arr包含的产品
                }
            }
            
            $amount = 0;
            foreach($order_goods as $gkey=>$gval) {
                $amount += bcmul($gval['goods_price'],$gval['goods_num'],2);
            }
            $per = "0%";
            if(time() >= $val['end_time']){
                if($amount >= $val['amount']){
                    $progress = 100;
                    $per = "100%";
                    if($val['status'] == 0){
                        $data['status'] = 1;
                        D('plan')->where('id='.$val['id'])->save($data);
                    }
                    $res[$key]['status'] = '已完成';
                }else{
                    $progress = $amount/$val['amount']*100;
                    $per = $amount/$val['amount']*100;
                    $per = $per."%";
                    if($val['status'] == 0){
                        $data['status'] = 2;
                        D('plan')->where('id='.$val['id'])->save($data);
                    }
                    $res[$key]['status'] = '未完成';
                }
            }
            
            $res[$key]['progress'] = $progress;
            $res[$key]['per'] = $per;
            $res[$key]['total'] = $amount?$amount:0;
            $res[$key]['tobedone'] = bcsub($val['amount'],$amount)>0?bcsub($val['amount'],$amount):0;
            $res[$key]['timegap'] = date('Y-m-d H:i:s', $val['start_time']).'-'.date('Y-m-d H:i:s', $val['end_time']);
        }
        
        
        
        $show = $Page->show();// 分页显示输出
        $this->assign('list',$res);// 赋值数据集
        $this->assign('type',$type);// 赋值数据集
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    //比较两个数组元素，排除相同元素内容后，返回剩余的$array1
    public function filter_array1_by_id($array1, $array2) {
        // 提取 $array2 中所有 id 值，转为快速查找的键名结构
        $array2_ids = array_flip(array_column($array2, 'goods_id'));
        
        // 过滤 $array1：只保留 $array2 中没有的 id
        $result = [];
        foreach ($array1 as $item) {
            if (!isset($array2_ids[$item['goods_id']])) {
                $result[] = $item;
            }
        }
        return $result;
    }
    
    //比较两个数组元素，排除不同元素内容后，返回剩余的$array1
    public function filter_array1_by_difid($array1, $array2) {
        // 将 $array2 的 ID 存入哈希表（快速查找）
        $id_map = array_flip(array_column($array2, 'goods_id'));
        
        // 过滤 $array1
        $result = [];
        foreach ($array1 as $item) {
            if (isset($id_map[$item['goods_id']])) {
                $result[] = $item;
            }
        }
        return $result;
    }
    
    public function addplan(){
        $act = I('act',false);
        $id = I('id',false);
        if(IS_POST){
            $user_id = $_POST['user_id'];
            $amount = $_POST['amount'];
            $start_time = $_POST['start_time'];
            $end_time = $_POST['end_time'];
            $cunstomer_id = $_POST['cunstomer_id'];
            $category_id = $_POST['category_id'];
            $excludecategory_id = $_POST['excludecategory_id'];
            
            if(empty($user_id)){
                $this->error("业务员不能为空！");
            }
            if(empty($amount)){
                $this->error("业绩不能为空！");
            }
            if(empty($start_time) || empty($end_time)){
                $this->error("时间不能为空！");
            }
            $start_time = strtotime($start_time);
            $end_time = strtotime($end_time);
            if($start_time >= $end_time){
                $this->error("开始时间不能大于等于结束时间！");
            }
            if(empty($cunstomer_id)){
                $this->error("客户不能为空！");
            }
            $category_arr = '';
            if(empty($category_id)){
                $category_arr = '0';//如果不选择就为0，默认全部分类都可以算业绩
            }
            
            $excludecategory_arr = '';
            if(empty($excludecategory_id)){
                $excludecategory_arr = '0';//如果不选择就为0，默认全部分类都可以算业绩
            }
            
            
            $users = M('staff')->where("user_id='$user_id'")->find();
            if(empty($users)){
                $this->error("业务员不存在");
            }
            $customer_arr = '';
            foreach($cunstomer_id as $key=>$val) {
                $customer_arr = $customer_arr.','.$val;
            }
            $customer_arr = substr($customer_arr, 1);
            
            if($category_id){
                foreach($category_id as $key=>$val) {
                    $category_arr = $category_arr.','.$val;
                }
                $category_arr = substr($category_arr, 1);
            }
            
            if($excludecategory_id){
                foreach($excludecategory_id as $key=>$val) {
                    $excludecategory_arr = $excludecategory_arr.','.$val;
                }
                $excludecategory_arr = substr($excludecategory_arr, 1);
            }
            
            $data['user_id'] = $user_id;
            $data['amount'] = $amount;
            $data['start_time'] = $start_time;
            $data['end_time'] = $end_time;
            $data['customer_id_arr'] = $customer_arr;
            $data['category_id_arr'] = $category_arr;
            $data['excludecategory_id_arr'] = $excludecategory_arr;
            $data['fenbu_id'] = $users['fenbu_id'];
            
            if(!$id){
                $r = D('plan')->add($data);
                if($r){
                    $this->success('任务添加成功',U('Crm/planList'));
                    exit;
                }else{
                    $this->error("任务更新失败");
                }
            }else{
                $r = D('plan')->where('id='.$id)->save($data);
                if($r){
                    $this->success('任务更新成功',U('Crm/planList'));
                    exit;
                }else{
                    $this->error("任务更新失败");
                }
            }
            
        }
        if($act == 'edit'){
            if(!$id){
                $this->error("参数错误");
            }
            $plan_data = D('plan')->where('id = '.$id)->find();
            $user_data = D('users')->where('user_id = '.$plan_data['user_id'])->find();
            $custom_data = D('users')->where('user_id in ('.$plan_data['customer_id_arr'].')')->select();
            $category_data = D('goods_category')->where('id in ('.$plan_data['category_id_arr'].')')->select();
            $excludecategory_data = D('goods_category')->where('id in ('.$plan_data['excludecategory_id_arr'].')')->select();
            $plan_data['user_name'] = $user_data['nickname'];
            $plan_data['company'] = $user_data['company'];
            $this->assign('custom_data',$custom_data);
            $this->assign('category_data',$category_data);
            $this->assign('excludecategory_data',$excludecategory_data);
            $this->assign('data',$plan_data);
        }else{
            $plan_data['start_time'] = strtotime(date('Y-m-d'));
            $plan_data['end_time'] = strtotime(date('Y-m-d'));
            $this->assign('data',$plan_data);
        }
        
        $this->display();
    }
    
    
    public function staffList(){
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    
    /**
     * 员工列表
     */
    public function staffajaxindex(){
        // 搜索条件
        $condition = array();
        I('fenbu_id') ? $condition['fenbu_id'] = I('fenbu_id') : false;
        I('mobile') ? $condition['c.mobile'] =['like',"%".I('mobile')."%"] : false;
        I('email') ? $condition['c.email'] = I('email') : false;
        I('user_id') ? $condition['a.user_id'] = I('user_id') : false;
        $nickname = trim(I('nickname'));
        $nickname ? $condition['_string'] =  ' (c.nickname like "%'.$nickname.'%") OR (c.company like "%'.$nickname.'%") OR (c.nick_name like "%'.$nickname.'%") ' :false;
        
        $condition['c.reg_time'] = ['between',[$this->begin,$this->end]];
        
        //$sort_order = "a.".I('order_by').' '.I('sort');
        $sort_order = "a.staff_id desc";
        $model = M('staff a');
        $count = $model
        ->join('ty_users c on c.user_id=a.user_id','LEFT')
        ->join('ty_region b on c.quyu=b.id','LEFT')
        ->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        // dump($condition);
        $userList = $model
        ->field('a.*,b.name,b.id quyu_id,c.*')
        ->join('ty_users c on c.user_id=a.user_id','LEFT')
        ->join('ty_region b on c.quyu=b.id','LEFT')
        ->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $show = $Page->show();
        $this->assign('userList',$userList);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    public function customerList(){
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->display();
    }
    
    public function customerajaxindex(){
        //parent_name
        // 搜索条件
        $condition = array();
        I('fenbu_id') ? $condition['fenbu_id'] = I('fenbu_id') : false;
        I('mobile') ? $condition['c.mobile'] =['like',"%".I('mobile')."%"] : false;
        I('email') ? $condition['c.email'] = I('email') : false;
        I('user_id') ? $condition['a.user_id'] = I('user_id') : false;
        $nickname = trim(I('nickname'));
        $nickname ? $condition['_string'] =  ' (c.nickname like "%'.$nickname.'%") OR (c.company like "%'.$nickname.'%") OR (c.nick_name like "%'.$nickname.'%") ' :false;
        
        $condition['c.reg_time'] = ['between',[$this->begin,$this->end]];
        
        //$sort_order = "a.".I('order_by').' '.I('sort');
        $sort_order = "a.cus_id desc";
        $model = M('customer a');
        $count = $model
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->join('ty_region b on c.quyu=b.id','LEFT')
        ->where($condition)->count();
        $Page  = new AjaxPage($count,10);
        //  搜索条件下 分页赋值
        foreach($condition as $key=>$val) {
            $Page->parameter[$key]   =   urlencode($val);
        }
        
        // dump($condition);
        $userList = $model
        ->field('a.*,b.name,b.id quyu_id,c.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->join('ty_region b on c.quyu=b.id','LEFT')
        ->where($condition)->order($sort_order)->limit($Page->firstRow.','.$Page->listRows)->select();
        
        foreach($userList as $key=>$val) {
            $userList[$key]['parent_name']= $val['user_id'] ? M('users')->where('user_id='.$val['user_id'])->getField('company') : '';
        }
        
        $show = $Page->show();
        $this->assign('userList',$userList);
        $this->assign('fenbu_list',$this->fenbu_list);
        $this->assign('page',$show);// 赋值分页输出
        $this->display();
    }
    
    /**
     * 搜索用户名
     */
    public function search_user()
    {
        $search_key = trim(I('search_key'));$store_id = trim(I('store_id'));$dai_type = trim(I('dai_type'));
        if($dai_type=='1'){
            $where="(c.mobile like'%$search_key%' or c.company like'%$search_key%') and c.is_lock=0 and c.store_id=".$store_id;
        }else{
            $where="c.mobile like'%$search_key%' or c.company like'%$search_key%' and c.is_lock=0 and c.store_id=0";
        }
        
        $list = M('staff a')
        ->field('c.*')
        ->join('ty_users c on c.user_id=a.user_id','LEFT')
        ->where($where)->select();
        
        if(empty($list)){
            echo \json_encode([
                'code'=>-1
            ]);
            return false;
        }
        
        foreach($list as $v){
            $list_s.='<li rel="'.$v['user_id'].'" rev="'.$v['mobile'].'" alt="'.$v['company'].'" class="'.$v['company_address'].'" title="'.$v['company'].'" id="'.$v['biaoshi_xian'].'">'.$v['company'].'：'.$v['company_address'].'</li>';
        }
        echo \json_encode([
            'code'=>'200',
            'selects'=>$list_s
        ]);
        exit;
    }
    
    //业绩计划搜索客户
    public function search_customers(){
        $where = '1=1';
        if(!empty($_REQUEST['keywords']))
        {
            $this->assign('keywords',I('keywords'));
            $search_key = I('keywords');
            $where = "$where and (c.mobile like'%$search_key%' or c.company like'%$search_key%') and c.is_lock=0";
        }
        
        $list = M('customer a')
        ->field('c.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->order("a.cus_id desc")->select();
        
        $this->assign('cunstomerlist',$list);
        $this->display();
    }
    
    /**
     * 搜索客户
     */
    public function search_customer()
    {
        $search_key = trim(I('search_key'));$store_id = trim(I('store_id'));$dai_type = trim(I('dai_type'));
        if($dai_type=='1'){
            $where="(c.mobile like'%$search_key%' or c.company like'%$search_key%') and c.is_lock=0 and c.store_id=".$store_id;
        }else{
            $where="c.mobile like'%$search_key%' or c.company like'%$search_key%' and c.is_lock=0 and c.store_id=0";
        }
        
        $list = M('customer a')
        ->field('c.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->select();
        
        if(empty($list)){
            echo \json_encode([
                'code'=>-1
            ]);
            return false;
        }
        
        foreach($list as $v){
            $list_s.='<li rel="'.$v['user_id'].'" rev="'.$v['mobile'].'" alt="'.$v['nickname'].'" class="'.$v['company_address'].'" title="'.$v['company'].'" id="'.$v['biaoshi_xian'].'">'.$v['company'].'：'.$v['company_address'].'</li>';
        }
        echo \json_encode([
            'code'=>'200',
            'selects'=>$list_s
        ]);
        exit;
    }
    
    public function addstaff(){
        $_id = $_GET['id'];
        $list =  M('staff')->where("user_id = ".$_id)->find();
        if(!empty($list)){
            $json_arr = array('code'=>-1,'msg'=>'此用户已添加，请勿重复添加');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $set = M("users")->where("user_id =".$_id)->find();
        $adddate = [];
        $adddate['user_id'] = $set['user_id'];
        $adddate['fenbu_id'] = $set['fenbu_id'];
        $data = M("staff")->add($adddate);
        if($data){
            $json_arr = array('code'=>200,'msg'=>'添加成功');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $json_arr = array('code'=>-1,'msg'=>'添加失败');
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    
    public function addcustom(){
        $_id = $_GET['id'];
        $list =  M('customer')->where("custom_id = ".$_id)->find();
        if(!empty($list)){
            $json_arr = array('code'=>-1,'msg'=>'此用户已添加，请勿重复添加');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $set = M("users")->where("user_id =".$_id)->find();
        $adddate['custom_id'] = $set['user_id'];
        $adddate['fenbu_id'] = $set['fenbu_id'];
        $data = M("customer")->add($adddate);
        if($data){
            $json_arr = array('code'=>200,'msg'=>'添加成功');
            $json_str = json_encode($json_arr);
            exit($json_str);
        }
        $json_arr = array('code'=>-1,'msg'=>'添加失败');
        $json_str = json_encode($json_arr);
        exit($json_str);
    }
    
    public function staff_sousuo(){
        $key=I('key');
        if($key){
            $fenlei=M('staff a')
            ->field('c.user_id,c.company,c.mobile')
            ->join('ty_users c on c.user_id=a.user_id','LEFT')
            ->where('c.company like "%'.$key.'%" or c.mobile like"%'.$key.'%"')->limit(15)->select();
            
            echo '<li rev="0,0,0" style="color:red">清理所属员工</li>';
            foreach($fenlei as $v){
                echo '<li rev="'.$v['user_id'].','.$v['company'].','.$v['mobile'].'">'.$v['company'].'</li>';
            }
        }
        exit;
    }
    
    public function staff_edit(){
        $id=I('id');$parent_id=I('parent_id');
        if($id){
            M('customer')->where('custom_id='.$id)->setField('user_id',$parent_id);
        }
        exit;
    }
    //任务详情
    public function detail(){
        $id = I('get.id');
        $visit_data = D('visit')->where(array('id'=>$id))->find();
        if(!$visit_data)
            exit($this->error('任务信息不存在'));
            
            $users_arr = [];
            $users = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
            foreach($users as $key=>$val) {
                $users_arr[$val['user_id']] = $val;
            }
            //$user_data = D('users')->where('user_id = '.$visit_data['user_id'])->find();
            $custom_data = D('users')->where('user_id = '.$visit_data['custom_id'])->find();
            $visit_data['custom_name'] = $custom_data['company'];
            $visit_data['user_name'] = $users_arr[$visit_data['user_id']]['company'];
            $visit_data['visit_time']= date('Y-m-d', $visit_data['visit_time']);
            $detail_data = D('visit_detail')->where(array('vis_id'=>$id))->select();
            foreach($detail_data as $key=>$val) {
                $detail_data[$key]['user_name']= $users_arr[$val['user_id']]['company'];
                $detail_data[$key]['type']= $val['type']?"签退":"签到";
                $detail_data[$key]['addtime']= date('Y-m-d H:i:s', $val['addtime']);
            }
            $this->assign('visit_data',$visit_data);
            $this->assign('detail_data',$detail_data);
            $this->display();
    }
    
    //下线详情
    public function xiaxians()
    {
        $user_id= I('user_id');
        $model = M("customer a");
        $where = "a.user_id = ".$user_id;
        $user_name="c.".I('user_name');
        if(I('user_name')){
            $where .= " and (c.company like '%".$user_name."%' or c.nick_name like '%".$user_name."%')";
        }
        
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }
        
        if($begin && $end){
            $where .= " and c.reg_time >=".strtotime($begin)." and c.reg_time<=".strtotime($end);
        }
        
        $count = $model
        ->field('a.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->select();
        
        $Page  = new Page(count($count),20);
        $list = $model
        ->field('c.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->order("a.user_id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->display();
    }
    
    public function export_xians()
    {
        $user_id= I('user_id');
        $model = M("customer a");
        $where = "a.user_id = ".$user_id;
        $user_name="c.".I('user_name');
        if(I('user_name')){
            $where .= " and (c.company like '%".$user_name."%' or c.nick_name like '%".$user_name."%')";
        }
        
        $timegap = I('timegap');
        $timegap = str_replace('+',' ',$timegap);
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = $gap[0];
            $end = $gap[1];
        }
        
        if($begin && $end){
            $where .= " and c.reg_time >=".strtotime($begin)." and c.reg_time<=".strtotime($end);
        }

		$list = $model
		->field('c.*')
		->join('ty_users c on c.user_id=a.custom_id','LEFT')
		->where($where)->order("a.cus_id desc")->select();
		
		
		$strTable ='<table width="500" border="1">';
		$strTable .= '<tr>';
		$strTable .= '<td style="text-align:center;font-size:12px;width:120px;">ID</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="160">会员昵称</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">公司/姓名</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">手机号码</td>';
		$strTable .= '<td style="text-align:center;font-size:12px;" width="*">注册日期</td>';
		$strTable .= '</tr>';
		
		foreach($list as $k=>$val){
		    $strTable .= '<tr>';
		    $strTable .= '<td style="text-align:center;font-size:12px;">&nbsp;'.$val['user_id'].'</td>';
		    $strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['nick_name'].' </td>';
		    $strTable .= '<td style="text-align:left;font-size:12px;">'.$val['company'].'</td>';
		    $strTable .= '<td style="text-align:left;font-size:12px;">&nbsp;'.$val['mobile'].'</td>';
		    $strTable .= '<td style="text-align:left;font-size:12px;">'.date('Y-m-d H:i:s', $val['reg_time']).'</td>';
		    $strTable .= '</tr>';
		}
		$strTable .='</table>';
		unset($list);
		downloadExcel($strTable,'下线导出');
		exit();
    }
    
    //下线详情
    public function customdetail()
    {
        $user_id= I('user_id');
        $id= I('id');
        if(!$id){
            $this->display();
        }
        $plan = M("plan")->where("id=".$id)->find();
        $customer_id_arr= $plan['customer_id_arr'];
        $model = M("customer a");
        $where = '1=1';
        $where .= " and a.custom_id in (".$customer_id_arr.")";
        if(I('user_name')){
            $user_name="c.".I('user_name');
            
            if($user_name){
                $where .= " and (c.company like '%".$user_name."%' or c.nick_name like '%".$user_name."%')";
            }
        }
        
        $count = $model
        ->field('a.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->select();
        
        $Page  = new Page(count($count),20);
        $list = $model
        ->field('c.*')
        ->join('ty_users c on c.user_id=a.custom_id','LEFT')
        ->where($where)->order("a.cus_id desc")->limit($Page->firstRow.','.$Page->listRows)->select();
        
        $show  = $Page->show();
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->display();
    }
    
    public function export_user(){
        import("Org.Util.PHPExcel");
        import("Org.Util.PHPExcel.Worksheet.Drawing");
        import("Org.Util.PHPExcel.Writer.Excel2007");
        $objPHPExcel = new \PHPExcel();
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        $objActSheet = $objPHPExcel->getActiveSheet();
        
        $objActSheet->setCellValue('A1', '任务名称');
        $objActSheet->setCellValue('B1', '预计拜访时间');
        $objActSheet->setCellValue('C1', '客户名称');
        $objActSheet->setCellValue('D1', '拜访目的');
        $objActSheet->setCellValue('E1', '业务员');
        $objActSheet->setCellValue('F1', '业绩');
        $objActSheet->setCellValue('G1', '备注');
        
        $i=2;
        
        $Visit =  M('visit');
        $where = "1=1";
        
        $keywords = I('keywords',false);
        if($keywords){
            $where .= " and visit_name like '%$keywords%'";
        }
        $user_name = I('user_name',false);
        $user_id = I('user_id',false);
        if($user_name && $user_id){
            $where .= " and user_id =".$user_id;
        }
        $timegap = I('timegap');
        if($timegap){
            $gap = explode(' - ', $timegap);
            $begin = strtotime($gap[0]);
            $end = strtotime($gap[1]);
        }
        if($begin && $end){
            $where .= " and visit_time >=".$begin." and visit_time<=$end";
        }
        
        
        $res = $Visit->where($where)->order('id desc')->select();
        
        $users_arr = [];
        $users = M('staff a')->join('ty_users c on c.user_id=a.user_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($users as $key=>$val) {
            $users_arr[$val['user_id']] = $val;
        }
        
        $customer_arr = [];
        $customer = M('customer a')->join('ty_users c on c.user_id=a.custom_id','LEFT')->cache(true,43200)->where("1=1")->select();
        foreach($customer as $key=>$val) {
            $customer_arr[$val['custom_id']] = $val;
        }
        
        foreach($res as $key=>$val) {
            if($users_arr[$val['user_id']]){
                $res[$key]['user_id'] = $users_arr[$val['user_id']]['company'];
            }
            if($customer_arr[['custom_id']]){
                $total = M('order')->where('order_status not in(3,4) and add_time >= '.$val['visit_time'].' and pay_status not in(3,5) and user_id='.$val['custom_id'])->sum('total_amount');
                $res[$key]['total'] = $total;
                $res[$key]['custom_id'] = $users_arr[$val['custom_id']]['company'];
            }
            $res[$key]['visit_time'] = date('Y-m-d H:i:s', $val['visit_time']);
            $visit_purpose ="";
            if($val['visit_purpose'] == 0){
                $visit_purpose = "收集客户需求";
            }elseif($val['visit_purpose'] == 1){
                $visit_purpose = "了解客户需求";
            }elseif($val['visit_purpose'] == 2){
                $visit_purpose = "方案沟通";
            }elseif($val['visit_purpose'] == 3){
                $visit_purpose = "商务洽谈";
            }else{
                $visit_purpose = "售后服务";
            }
            
            $res[$key]['visit_purpose'] = $visit_purpose;
        }
        
        foreach($res as $v){
            $objActSheet->setCellValue('A'.$i, $v['visit_name']);
            $objActSheet->setCellValue('B'.$i, $v['visit_time']);
            $objActSheet->setCellValue('C'.$i, $v['custom_id']);
            $objActSheet->setCellValue('D'.$i, $v['visit_purpose']);
            $objActSheet->setCellValue('E'.$i, $v['user_id']);
            $objActSheet->setCellValue('F'.$i, $v['total']);
            $objActSheet->setCellValue('G'.$i, $v['remark']);
            
            $i++;
        }
        $fileName = '拜访任务信息';
        $date = date("Y-m-d",time());
        $fileName .= "_{$date}.xls";
        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        $objPHPExcel->getActiveSheet()->setTitle('任务信息');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output'); //文件通过浏览器下载
        exit;
    }
    
    public function delete(){
        $uid = I('get.id');
        $visit_pd=M('visit')->where('user_id='.$uid)->find();
        $plan_pd=M('plan')->where('user_id='.$uid)->find();
        if($visit_pd){
            $this->error('该员工已经存在拜访任务，禁止删除！');
            exit;
        }elseif($plan_pd){
            $this->error('该员工已经存在业绩任务，禁止删除！');
            exit;
        }else{
            M('staff')->where(array('user_id'=>$uid))->delete();$this->success('成功删除员工');
        }
    }
    
    //业绩计划搜索产品分类
    public function search_goods(){
        $where = '1=1';
//         if(!empty($_REQUEST['keywords']))
//         {
//             $this->assign('keywords',I('keywords'));
//             $search_key = I('keywords');
//             $where = "$where and (c.mobile like'%$search_key%' or c.company like'%$search_key%') and c.is_lock=0";
//         }
        $where = "$where and level=2";
        $list = M('goods_category a')
        ->where($where)->select();
        
        $this->assign('categorylist',$list);
        $this->display();
    }
    
    //业绩计划搜索产品分类
    public function selectexcludeGoods(){
        $where = '1=1';
        //         if(!empty($_REQUEST['keywords']))
            //         {
            //             $this->assign('keywords',I('keywords'));
            //             $search_key = I('keywords');
            //             $where = "$where and (c.mobile like'%$search_key%' or c.company like'%$search_key%') and c.is_lock=0";
            //         }
        $where = "$where and level=2";
        $list = M('goods_category a')
        ->where($where)->select();
        
        $this->assign('categorylist',$list);
        $this->display();
    }
}

